package org.example.domain;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 简化继承UserDetails的实现类User，作用于SpringSecurity
 *
 * 使用redis存储此对象时，redis的redisTemplate需要序列化，否者会乱码
 * 但GrantedAuthority这类（目前不知道为什么）不能序列化，权限信息又不能省略，采用额外的String类型存储
 * 序列化需要无参构造器和getter和setter方法，需要加@Data和@NoArgsConstructor
 */

@Data
@NoArgsConstructor
public class LoginUser implements UserDetails{

    private User user;

    private List<String> permissions;

    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    public org.example.domain.User getUser() {
        return user;
    }

    public void setUser(org.example.domain.User user) {
        this.user = user;
    }

    public LoginUser(String username, String password, List<String> permissions) {
        user.setUsername(username);
        user.setPassword(password);
        this.permissions = permissions;
    }

    public LoginUser(org.example.domain.User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

/*    public LoginUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        user.setUsername(username);
        user.setPassword(password);
        this.authorities = (List<GrantedAuthority>) authorities;
    }

    public LoginUser(org.example.domain.User user, Collection<? extends GrantedAuthority> authorities) {
        this.user = user;
        this.authorities = (List<GrantedAuthority>) authorities;
    }*/

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        if(authorities!=null){
            return authorities;
        }
        authorities = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return this.user.getPassword();
    }

    @Override
    public String getUsername() {
        return this.user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public String toString() {
        return "LoginUser{" +
                "user=" + user +
                ", permissions=" + permissions +
                '}';
    }
}
